import json

from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponsePermanentRedirect, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from courses.models import Course
from operation.models import UserCourse, UserMessage, UserFavorite
from organization.models import CourseOrg, Teacher
from .models import UserProfile
from . import constants
from users.forms import RegisterForm, LoginForm, ForgetForm, ModifyPwdForm, UserInfoForm
from utils.boxuegu_signature import dumps, loads
from celery_tasks.mail.tasks import send_user_mail


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})

    def post(self, request):
        data = request.POST
        register_form = RegisterForm(data)
        res = register_form.is_valid()
        if res:
            cleaned_data = register_form.cleaned_data
            # 验证邮箱是否重复
            if UserProfile.objects.filter(email=cleaned_data['email']).count() > 0:
                return render(request, 'register.html', {'msg': '该邮箱已被注册!!!'})
            cleaned_data.pop('captcha')
            cleaned_data['username'] = cleaned_data['email']

            user = UserProfile.objects.create_user(**cleaned_data)
            login(request, user)
            # return HttpResponsePermanentRedirect(reverse('index'))
            return redirect(reverse('index'))
            # return render(request, 'index.html')
        return render(request, 'register.html', {'register_form': register_form})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        data = request.POST
        login_form = LoginForm(data)
        res = login_form.is_valid()
        if res:
            cleaned_data = login_form.cleaned_data
            user = authenticate(username=cleaned_data['email'], password=cleaned_data['password'])
            if user is None:
                return render(request, 'login.html', {'msg': '邮箱或密码填写错误!!!'})
            else:
                login(request, user)
                return HttpResponsePermanentRedirect(reverse('index'))

        return render(request, 'login.html', {'form_errors': login_form.errors})


class LogoutView(View):
    def get(self, request):
        logout(request)
        return redirect(reverse('index'))


class ForgetPwdView(View):
    def get(self, request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    def post(self, request):
        forget_form = ForgetForm(request.POST)
        res = forget_form.is_valid()
        if res:
            email = forget_form.cleaned_data['email']
            if UserProfile.objects.filter(email=email).count() == 0:
                return render(request, 'forgetpwd.html', {'msg': '该邮箱没有被注册!!!'})
            token = dumps({'user_id': UserProfile.objects.get(email=email).id},
                          constants.EMAIL_RESET_EXPIRES)
            url = settings.EMAIL_RESET_URL + token
            send_user_mail.delay(email, url)
            return render(request, 'send_success.html')

        return render(request, 'forgetpwd.html', {'forget_form': forget_form})


class ResetView(View):
    def get(self, request, active_code):
        dic1 = loads(active_code, constants.EMAIL_RESET_EXPIRES)
        if dic1 is None:
            return render(request, 'active_fail.html')
        email = UserProfile.objects.get(id=dic1['user_id']).email
        return render(request, 'password_reset.html', {'email': email})


class ModifyView(View):
    def post(self, request):
        data = request.POST
        modify_form = ModifyPwdForm(data)
        res = modify_form.is_valid()
        if res:
            modify_form = modify_form.cleaned_data
            if modify_form['password1'] != modify_form['password2']:
                return render(request, 'password_reset.html', {'msg': '2次密码不一致!!!'})
            # 修改密码成功返回登录页面
            user = UserProfile.objects.get(email=data.get('email'))
            user.set_password(modify_form['password1'])
            user.save()
            return HttpResponsePermanentRedirect(reverse('login'))
        return render(request, 'password_reset.html', {'modify_form': modify_form})


class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'usercenter-info.html', {'MEDIA_URL': settings.MEDIA_URL})

    def post(self, request):
        data = request.POST
        userinfo_form = UserInfoForm(data)
        res = userinfo_form.is_valid()
        if res:
            userinfo_form = userinfo_form.cleaned_data
            UserProfile.objects.filter(id=request.user.id).update(**userinfo_form)
            return JsonResponse({"status": "success"})
        else:
            return JsonResponse({"status": "error"})


class UploadImageView(LoginRequiredMixin, View):
    def post(self, request):
        pass


class MyCourseView(LoginRequiredMixin, View):
    def get(self, request):
        user_courses = UserCourse.objects.filter(user=request.user)
        return render(request, 'usercenter-mycourse.html', {
            'user_courses': user_courses,
            'MEDIA_URL': settings.MEDIA_URL
        })


class MyFavOrgView(LoginRequiredMixin, View):
    def get(self, request):
        querry_set = UserFavorite.objects.filter(user=request.user, fav_type=2)
        ids_list = [item.fav_id for item in querry_set]
        org_list = [CourseOrg.objects.get(id=id) for id in ids_list]
        # 'org_id': id,
        # 'org': CourseOrg.objects.get(id=id)
        return render(request, 'usercenter-fav-org.html', {
            'org_list': org_list,
            'MEDIA_URL': settings.MEDIA_URL
        })


class MyFavTeacherView(LoginRequiredMixin, View):
    def get(self, request):
        querry_set = UserFavorite.objects.filter(user=request.user, fav_type=3)
        ids_list = [item.fav_id for item in querry_set]
        teacher_list = [Teacher.objects.get(id=id) for id in ids_list]
        return render(request, 'usercenter-fav-teacher.html', {
            'teacher_list': teacher_list,
        })


class MyFavCourseView(LoginRequiredMixin, View):
    def get(self, request):
        querry_set = UserFavorite.objects.filter(user=request.user, fav_type=1)
        ids_list = [item.fav_id for item in querry_set]
        course_list = [Course.objects.get(id=id) for id in ids_list]
        return render(request, 'usercenter-fav-course.html', {
            'course_list': course_list,
        })


class MyMessageView(LoginRequiredMixin, View):
    def get(self, request):
        messages = UserMessage.objects.filter(user=request.user.id)
        return render(request, 'usercenter-message.html', {
            'messages': messages,
        })
